import { ref, onMounted } from "vue";
import { Area, Country } from "@/api/interface";
import { getProvince, getCity, getDistrict, getCountryList } from "@/api/modules/sys"; //getDict

export const useAddress = () => {
  let countryList = ref<Country[]>([]);
  let areaList = ref<Area[]>();
  let defaultOptions = ref({});

  let resolve: any;
  const promise = new Promise(res => {
    resolve = res;
    // reject = rej;
  });

  // 获取国家
  const getCountryListFn = async () => {
    const { data } = await getCountryList();
    countryList.value = data || [];
  };
  const getCitys = async (params: Area) => {
    const { data } = await getCity(params);
    return data || [];
  };
  const getDistricts = async (params: Area) => {
    const { data } = await getDistrict(params);
    return data || [];
  };
  // 省市区
  defaultOptions.value = {
    lazy: true,
    label: "name",
    value: "code",
    checkStrictly: true,
    lazyLoad: async (node: Node, resolve: (data: Area) => void) => {
      let data = [];
      if (node.level === 1) {
        data = await getCitys({ code: node.data.code });
      } else if (node.level === 2) {
        data = await getDistricts({ code: node.data.code });
      }
      data = data.map(item => {
        item.leaf = node.level >= 2;
        return item;
      });
      resolve(data);
    }
  };

  onMounted(async () => {
    await getCountryListFn();
    // 获取省份
    const { data } = await getProvince();
    areaList.value = data;
    resolve(data);
  });

  return {
    countryList,
    defaultOptions,
    areaList,
    promise
  };
};
